package com.zj.framework.okhttp;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xi.yang(xi.yang@downjoy.com)
 * @create 2018-05-29 下午 3:24
 **/
public class ZyltMessage {
    private static final int CONNECTION_TIMEOUT = 5 * 1000;

    private static final int REQUEST_TIMEOUT = 10 * 1000;

    public static void main(String[] args) {
        RequestData requestData = getRequestData();
        requestData.getCookies().put("pgv_info", "ssi=s865740585");
        System.out.println(JSON.toJSONString(requestData));
        requestData.getForm().put("message","老王，再搞不定就莫法了");
        String sendMessage = sendMessage(requestData);
        System.out.println("==========="+sendMessage);
    }

    public static String sendMessage(RequestData requestData) {
        CookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)
                .build();
        try {
            String url = requestData.getUrl();
            for (String k : requestData.getCookies().keySet()) {
                BasicClientCookie cookie = new BasicClientCookie(k,requestData.getCookies().get(k));
                cookie.setVersion(0);
                cookie.setDomain("bbs.zhiyoo.com");
                cookie.setPath("/");
                cookieStore.addCookie(cookie);
            }
            List<NameValuePair> nvpsList = new ArrayList<NameValuePair>();
            if(requestData.getForm() != null){
                for (String key : requestData.getForm().keySet()) {
                    nvpsList.add(new BasicNameValuePair(key, requestData.getForm().get(key)));
                }
            }
            String connectUrl = HttpUtil.buildGetUrl(url, nvpsList);
            HttpPost httpPost = new HttpPost(connectUrl);
            httpPost.addHeader("X-Requested-With","XMLHttpRequest");
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(REQUEST_TIMEOUT).setConnectTimeout(CONNECTION_TIMEOUT).build();
            httpPost.setConfig(requestConfig);
            HttpResponse response = httpClient.execute(httpPost);
            System.out.println(JSON.toJSONString(response));
            return response.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }finally{

        }
        return "error ";
    }

    public static RequestData getRequestData() {
        RequestData requestData = new RequestData();
        Map<String,String> cookies = new HashMap<>();
        Map<String,String> headers = new HashMap<>();
        Map<String,String> form = new HashMap<>();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\zylt.txt")),
                    "UTF-8"));
            String lineTxt = null;
            while ((lineTxt = br.readLine()) != null) {
                if (lineTxt.contains("POST")) {
                    requestData.setUrl(lineTxt.split(" ")[1]);
                    continue;
                }
                if (lineTxt.contains("&") && !lineTxt.contains("POST") && !lineTxt.contains("Referer")) {
                    lineTxt = lineTxt.replace("form-data:", "");
                    String[] strs = lineTxt.split("&");
                    for (String str : strs) {
                        String[] kv = str.split("=");
                        form.put(kv[0].trim(),kv[1].trim());
                    }
                    continue;
                }
                if(lineTxt.contains("Cookie")){
                    lineTxt = lineTxt.replace("Cookie:","");
                    String[] strs = lineTxt.split(";");
                    for (String str : strs) {
                        String[] kv = str.split("=");
                        cookies.put(kv[0].trim(),kv[1].trim());
                    }
                    continue;
                }
                if (lineTxt.contains(":")) {
                    String[] strs = lineTxt.split(":");
                    headers.put(strs[0], strs[1]);
                }
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        requestData.setHeaders(headers);
        requestData.setCookies(cookies);
        requestData.setForm(form);
        return requestData;
    }
}

class RequestData {
    private String url;
    private Map<String, String> cookies;
    private Map<String, String> headers;
    private Map<String,String> form;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }

    public Map<String, String> getCookies() {
        return cookies;
    }

    public void setCookies(Map<String, String> cookies) {
        this.cookies = cookies;
    }

    public Map<String, String> getForm() {
        return form;
    }

    public void setForm(Map<String, String> form) {
        this.form = form;
    }
}
